package io.gitee.zhangbinhub.admin.gateway.conf

import io.gitee.zhangbinhub.acp.boot.tools.EnvironmentTools
import io.gitee.zhangbinhub.admin.common.constant.RouteConstant
import org.springframework.boot.SpringApplication
import org.springframework.boot.env.EnvironmentPostProcessor
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.util.MimeTypeUtils

/**
 * @since JDK 11
 */
class RouteEnvironmentPostProcessor : EnvironmentPostProcessor {
    private val defaultPropertiesName = "acpCloudRouteDefaultProperties"
    private fun initProducer(environment: ConfigurableEnvironment) {
        val default: MutableMap<String, Any> = HashMap()
        "spring.cloud.stream.bindings.${RouteConstant.ROUTE_LOG_OUTPUT}".let { prefix ->
            environment.getProperty("$prefix.destination", RouteConstant.ROUTE_LOG_DESCRIPTION).let { destination ->
                if (destination == RouteConstant.ROUTE_LOG_OUTPUT) {
                    RouteConstant.ROUTE_LOG_DESCRIPTION
                } else {
                    destination
                }
            }.let { destination ->
                default["$prefix.destination"] = destination
                default["$prefix.contentType"] = MimeTypeUtils.APPLICATION_JSON_VALUE
                EnvironmentTools.addOrReplaceProperty(
                    environment.propertySources,
                    default,
                    defaultPropertiesName,
                    false
                )
            }
        }
    }

    override fun postProcessEnvironment(environment: ConfigurableEnvironment?, application: SpringApplication?) {
        initProducer(environment!!)
    }
}
